﻿using System.Collections.ObjectModel;
using System.Linq;
using Results.Models;

namespace Results.ViewModels
{
    /// <summary>
    /// The filtered rankings for a given group and season
    /// </summary>
    public class RankingsViewModel : ViewModelBase
    {
        /// <summary>
        /// The filtered rankings for a given group and season
        /// </summary>
        public ObservableCollection<RankingViewModel> Rankings { get; private set; }

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="resultsModel">Source data</param>
        public RankingsViewModel(ResultsModel resultsModel)
        {
            Rankings = new ObservableCollection<RankingViewModel>();
            _resultsModel = resultsModel;
        }

        /// <summary>
        /// Populate with all rankings (players) for the selected group and season
        /// </summary>
        /// <param name="selectedGroup">e.g. "Men 14-16"</param>
        /// <param name="selectedSeason">e.g. "2010"</param>
        /// <param name="notifyPlayerSelected">Methods to call if the user selects something</param>
        public void Query(string selectedGroup, string selectedSeason, INotifySelection notifyPlayerSelected)
        {
            Rankings.Clear();

            foreach (var ranking in
                from result in _resultsModel
                where result.Group == selectedGroup && result.TournamentModel.Season == selectedSeason
                group result by result.PlayerModel into ranking
                orderby ranking.Sum(result => result.PointValue) descending, ranking.Key
                select new { PlayerModel = ranking.Key, Points = ranking.Sum(result => result.PointValue) })
            {
                Rankings.Add(new RankingViewModel(ranking.PlayerModel, ranking.Points, notifyPlayerSelected) );
            }
        }

        readonly ResultsModel _resultsModel;
    }
}
